import { defineStore } from 'pinia';
import { searchApi } from '../api/services.js';

export const useSearchStore = defineStore('search', {
  state: () => ({
    searchResults: [],
    searchHistory: [],
    hotKeywords: [],
    loading: false,
    pagination: {
      page: 1,
      pageSize: 20,
      total: 0
    },
    filters: {
      category: '',
      sortBy: 'relevance', // relevance, date, popularity
      dateRange: ''
    }
  }),

  getters: {
    hasResults: (state) => state.searchResults.length > 0,
    hasMore: (state) => {
      const { page, pageSize, total } = state.pagination;
      return page * pageSize < total;
    }
  },

  actions: {
    /**
     * 搜索内容
     * @param {string} query - 搜索关键词
     * @param {Object} options - 搜索选项
     * @returns {Promise<Object>} 搜索结果
     */
    async search(query, options = {}) {
      if (!query.trim()) {
        this.searchResults = [];
        return { results: [], total: 0 };
      }

      this.loading = true;
      try {
        const searchParams = {
          q: query.trim(), // 修正参数名，后端期望'q'而不是'query'
          page: options.page || 1,
          limit: options.pageSize || this.pagination.pageSize, // 修正参数名，后端期望'limit'而不是'pageSize'
          category: options.category || this.filters.category,
          sort: options.sortBy || this.filters.sortBy, // 修正参数名，后端期望'sort'而不是'sortBy'
          // 移除dateRange参数，后端API不支持此参数
        };

        const searchData = await searchApi.search(searchParams);
        
        // 如果是新搜索（第一页），替换结果；如果是加载更多，追加结果
        const results = searchData.data?.results || searchData.results || []; // 适配后端响应格式
        if (searchParams.page === 1) {
          this.searchResults = results;
        } else {
          this.searchResults.push(...results);
        }
        
        // 更新分页信息
        this.pagination = {
          page: searchParams.page,
          pageSize: searchParams.limit, // 使用修正后的参数名
          total: searchData.data?.total || searchData.total || 0 // 适配后端响应格式
        };
        
        // 添加到搜索历史
        this.addToHistory(query);
        
        return searchData;
      } catch (error) {
        console.error('搜索失败:', error);
        this.searchResults = [];
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 加载更多搜索结果
     * @param {string} query - 搜索关键词
     * @returns {Promise<Object>} 搜索结果
     */
    async loadMore(query) {
      if (!this.hasMore || this.loading) {
        return;
      }
      
      return await this.search(query, {
        page: this.pagination.page + 1,
        ...this.filters
      });
    },

    /**
     * 设置搜索过滤器
     * @param {Object} filters - 过滤器选项
     */
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters };
    },

    /**
     * 清除搜索结果
     */
    clearResults() {
      this.searchResults = [];
      this.pagination = {
        page: 1,
        pageSize: 20,
        total: 0
      };
    },

    /**
     * 添加到搜索历史
     * @param {string} query - 搜索关键词
     */
    addToHistory(query) {
      const trimmedQuery = query.trim();
      if (!trimmedQuery) return;
      
      // 移除重复项
      this.searchHistory = this.searchHistory.filter(item => item !== trimmedQuery);
      // 添加到开头
      this.searchHistory.unshift(trimmedQuery);
      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10);
      }
      
      // 保存到本地存储
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
    },

    /**
     * 清除搜索历史
     */
    clearHistory() {
      this.searchHistory = [];
      localStorage.removeItem('searchHistory');
    },

    /**
     * 删除单个搜索历史项
     * @param {string} query - 要删除的搜索关键词
     */
    removeFromHistory(query) {
      this.searchHistory = this.searchHistory.filter(item => item !== query);
      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
    },

    /**
     * 获取热门搜索关键词
     * @param {number} limit - 返回数量限制
     * @returns {Promise<Array>} 热门关键词列表
     */
    async fetchHotKeywords(limit = 10) {
      try {
        const hotKeywordsData = await searchApi.getHotKeywords(limit);
        console.log('API返回的热门关键词数据:', hotKeywordsData);
        this.hotKeywords = hotKeywordsData.data?.keywords || [];
        return this.hotKeywords;
      } catch (error) {
        console.error('获取热门关键词失败:', error);
        this.hotKeywords = ['ChatGPT', 'Midjourney', '文心一言', 'Stable Diffusion', 'Claude'];
        return this.hotKeywords;
      }
    },

    /**
     * 获取搜索建议
     * @param {string} query - 搜索关键词前缀
     * @param {number} limit - 返回数量限制
     * @returns {Promise<Array>} 搜索建议列表
     */
    async getSuggestions(query, limit = 5) {
      if (!query || query.trim().length < 2) {
        return [];
      }
      
      try {
        const suggestionsData = await searchApi.getSuggestions(query.trim(), limit);
        return suggestionsData.suggestions || suggestionsData.data?.suggestions || [];
      } catch (error) {
        console.error('获取搜索建议失败:', error);
        return [];
      }
    },

    /**
     * 获取工具分类
     * @returns {Promise<Array>} 工具分类列表
     */
    async fetchCategories() {
      try {
        const categoriesData = await searchApi.getCategories();
        console.log('API返回的分类数据:', categoriesData);
        return categoriesData.categories || categoriesData.data?.categories || [];
      } catch (error) {
        console.error('获取工具分类失败:', error);
        return [];
      }
    },

    /**
     * 获取热门工具
     * @param {number} limit - 返回数量限制
     * @param {string} category - 分类过滤
     * @returns {Promise<Array>} 热门工具列表
     */
    async fetchPopularTools(limit = 10, category = '') {
      try {
        const popularToolsData = await searchApi.getPopularTools(limit, category);
        console.log('API返回的热门工具数据:', popularToolsData);
        return popularToolsData.tools || popularToolsData.data?.tools || [];
      } catch (error) {
        console.error('获取热门工具失败:', error);
        return [];
      }
    },

    /**
     * 记录工具点击
     * @param {number} toolId - 工具ID
     * @returns {Promise<boolean>} 记录是否成功
     */
    async recordToolClick(toolId) {
      try {
        await searchApi.recordClick(toolId);
        return true;
      } catch (error) {
        console.error('记录工具点击失败:', error);
        return false;
      }
    },

    /**
     * 初始化搜索历史
     */
    initializeHistory() {
      const savedHistory = localStorage.getItem('searchHistory');
      if (savedHistory) {
        try {
          this.searchHistory = JSON.parse(savedHistory);
        } catch (error) {
          console.error('解析搜索历史失败:', error);
          this.searchHistory = [];
        }
      }
    },

    /**
     * 搜索用户作品
     * @param {string} query - 搜索关键词
     * @param {Object} options - 搜索选项
     * @returns {Promise<Object>} 用户作品搜索结果
     */
    async searchWorks(query, options = {}) {
      this.loading = true;
      try {
        const searchParams = {
          query: query.trim(),
          page: options.page || 1,
          pageSize: options.pageSize || this.pagination.pageSize,
          category: options.category || '',
          sortBy: options.sortBy || 'relevance'
        };

        const worksData = await searchApi.searchWorks(searchParams);
        return worksData;
      } catch (error) {
        console.error('搜索作品失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 搜索竞赛
     * @param {string} query - 搜索关键词
     * @param {Object} options - 搜索选项
     * @returns {Promise<Object>} 竞赛搜索结果
     */
    async searchContests(query, options = {}) {
      this.loading = true;
      try {
        const searchParams = {
          query: query.trim(),
          page: options.page || 1,
          pageSize: options.pageSize || this.pagination.pageSize,
          status: options.status || '',
          category: options.category || ''
        };

        const contestsData = await searchApi.searchContests(searchParams);
        return contestsData;
      } catch (error) {
        console.error('搜索竞赛失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    /**
     * 搜索用户
     * @param {string} query - 搜索关键词
     * @param {Object} options - 搜索选项
     * @returns {Promise<Object>} 用户搜索结果
     */
    async searchUsers(query, options = {}) {
      this.loading = true;
      try {
        const searchParams = {
          query: query.trim(),
          page: options.page || 1,
          pageSize: options.pageSize || this.pagination.pageSize
        };

        const usersData = await searchApi.searchUsers(searchParams);
        return usersData;
      } catch (error) {
        console.error('搜索用户失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});